<template>
  <div class="contain">
      <!-- 代码添加 -->
      <el-card class="box-card">
          <!-- 头部展示 -->
          <Top @sendkey="finditems" @handleadduser="handleadduser"></Top>
          <!--  数据展示 -->
            <app-body :newlists="newlists" :defaultavater="defaultavater"
                      @deleteitem="deleteitem" @edititem="edititem"
                      @edituserinfo="edituserinfo">
            </app-body>
          <!-- 分页处理 -->
           <!-- 分页处理 -->
            <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    background
                    :page-size="5"
                    layout="total,pager"
                    :total="total">
            </el-pagination>
      </el-card>
  </div>
</template>

<script>
import request from './network'
import Top from './components/Top'
import AppBody from './components/AppBody'
export default {
  async created () {
    const  {data:res}   = await request.get('/api/getall') 
    this.lists = res.list
    this.newlists = res.list
    this.total = res.list.length

    // 获取第一页
      this.handleCurrentChange(this.currentPage)
  },
  data() {
    return {
      lists:[],
      newlists:[],
      defaultavater:"http://img.mp.itc.cn/upload/20170808/5861bc790e654d56bc9289c567b44875_th.jpg",
      total:0,
      currentPage:1,
    };
  },
  components: {
    Top,
    AppBody
  },
  methods: {
    // 完成修改逻辑
    edititem(id){
        
    },
    // 完成删除逻辑
    deleteitem(id){
      // 先找到要删除item 对应的下表索引
      let i = 1;
      i =  this.lists.findIndex((item)=>item.id==id)
      this.total--
      // 删除对应下标item
      this.lists.splice(i,1)
      this.handleCurrentChange(this.currentPage)

    },
    // 处理搜索框搜索
    finditems(keyword){
      // 先筛选出新的数组
      this.newlists = this.lists.filter((item)=>item.name.includes(keyword)).slice((this.currentPage-1)*5,5*this.currentPage)
    },
    // 处理具体添加逻辑
    handleadduser(userinfo){
      let id = this.lists[this.lists.length-1].id+1
      let obj = {...userinfo,id:id}
      this.total++
      // 数组追加
      this.lists.push(obj)
      this.handleCurrentChange(this.currentPage)
    },
    // 点击了确认修改后
    edituserinfo(obj){
      // 通过id 找到具体对应的数据 然后替换它
      let oldobj = this.lists.findIndex(item=>item.id==obj.id)
      this.lists.splice(oldobj,1,obj)
    },
     //
    handleCurrentChange(e){
        this.currentPage = e 
        this.newlists =  this.lists.slice((this.currentPage-1)*5,5*this.currentPage)
    }
  }

};
</script>

<style scoped>
  .contain{
    width: 1000px;
    margin: 50px auto;
  }
 .el-pagination{
   margin-top: 10px;
   display: flex;
   justify-content: center;
  }
  
</style>